import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import mail from './../../images/mail.png'
import mailOpen from './../../images/mail-open.png'
import AddOrEditUser from './addOrEditUser'
import DetailInfo from './Detail'
import AddOrEditStaffs from '../Staffs/AddOrEdit';
import AddOrEditDMAGraph from "./AddOrEditDMAGraph";
import Meters from './Meters'
import Workstation from './Workstation'
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ DMA_manage, loading,global }) => ({
  DMA_manage,
  global,
  loading: loading.models.DMA_manage,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      DMA_manage: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        DMA_manage: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'DMA_manage/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'DMA_manage/changeLoaded',
          });
          dispatch({
            type: 'DMA_manage/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_manage/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_manage/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_manage/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      DMA_manage: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
        {/*  <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>*/}
            <Button
              icon="plus"
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加DMA分区
            </Button>

        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'DMA_manage/add',
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
      },
      callback() {
        message.success('添加小区成功');
        that.setState({
          addModal: false,
        });
        const {
          DMA_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      username: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `DMA_manage/edit`,
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改小区成功');
        that.setState({
          editModal: false,
        });
        const {
          DMA_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `DMA_manage/remove`,
      payload: { id },
      callback: () => {
        message.success('删除小区成功');
        const {
          DMA_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  render() {
    const that = this;
    const {
      DMA_manage: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: '25%'
      },
      {
        title: '是否存在图关系',
        dataIndex: 'graph',
        key: 'graph',
        width: '25%',
        render: (val, record, index) => {
          return  <Fragment>
            {
              record.graph.edges.length>0?<p className="table-success table-status">存在</p>:<p className="table-error table-status">不存在</p>
            }
          </Fragment>
            }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: '20%',

      },
      {
        title: '操作',
        key: 'operate',
        classname:'operate',
        render: (val, record, index) => {
        return  <Fragment>
          <Button
            type="primary"
            size="small"
            icon="edit"
            onClick={(e) => {
              this.setState({
                editRecord:record,
                graphModal: true,
              });
            }
            }
          >编辑图关系
          </Button>
          <Button
            type="primary"
            size="small"
            className={'btn-cyn'}
            icon="edit"
            onClick={(e) => {
              this.setState({
                editRecord:record,
                editModal: true,
              });
            }
            }
          >编辑
          </Button>
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要删除"${record.name}"吗?`,
                  content: '删除后数据不可逆，请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered:true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(record.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除
            </Button>

        </Fragment>
        }
      }

    ]


    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>DMA设置</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div size="large" className="table-info-right-item" style={{ marginBottom: '28px' }}>
              <Button
                icon="plus"
                style={{marginRight:'6px'}}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加DMA分区
              </Button>
            <Button
              icon="setting"
              style={{marginRight:'6px'}}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    meterModal: true,
                  });
                }
              }
            >
              设置水表
            </Button>
            <Button
              icon="setting"
              type="primary"
              onClick={
                () => {
                  this.setState({
                    workstationModal: true,
                  });
                }
              }
            >
              设置工作站
            </Button>
          </div>
        </div>
        <div className={'table-data-content'}>
          <Table
            className='meter-table ant-table-interval'
            loading={loading}
            rowKey={record => record.id}
            dataSource={data}
            columns={columns}
            scroll={{y: tableY}}
            bordered
            pagination={false}
            size="small"
          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
      <div className="table-pagination">
        {/* <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/> */}
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加DMA分区"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        destroyOnClose
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={()=> {
          this.setState({addModal: false})
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.meterModal} modalClass="meterModal" title="设置水表"/>}
        className="meterModal"
        visible={this.state.meterModal}
        centered
        width={1250}
        onCancel={()=> {
          this.setState({meterModal: false})
        }}
        footer={null}
      >
        <Meters
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.workstationModal} modalClass="workstationModal" title="设置工作站点"/>}
        className="workstationModal"
        visible={this.state.workstationModal}
        centered
        width={1250}
        onCancel={()=> {
          this.setState({workstationModal: false})
        }}
        footer={null}
      >
        <Workstation
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        className="editModal"
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}
        onOk={this.handleEdit}
      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
      <Drawer
        title={`编辑”${this.state.editRecord.name}“图关系`}
        placement="right"
        destroyOnClose
        keyboard={false}
        onClose={() => {
          this.setState({
            graphModal: false,
            editRecord: {},
          });
        }}

        width={'100vw'}
        visible={this.state.graphModal}
      >
        <AddOrEditDMAGraph
          onClose={() => {
            this.setState({
              graphModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          onSave={this.handleAdd}
          handleSearch={()=>{
            this.handleSearch(searchParams)
          }}
          cancel={()=>{
            this.setState({
              graphModal: false,
              editRecord: {},
            });
          }}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
    </div>;
  }
}

export default BasicList;
